﻿using System;
using System.Text;

namespace PacketRush.Core
{
    public class ServerTestService : INetService
    {
        private NetServer _NetServer { get; set; }

        /// <summary>
        /// How many outgoing packets the test service will create before each update
        /// </summary>
        public int PacketsPerUpdate { get; set; }

        private int _OutgoingPacketCounter = 0;
        private Packet _TestPacket;
        PacketReader _PacketReader = new PacketReader();
        public ServerTestService(bool reliable)
        {
            PacketsPerUpdate = 10;

            PacketWriter writer = new PacketWriter();
            writer.Write("Hello World", Encoding.UTF8);
            _TestPacket = writer.ToPacket(PacketFlags.Reliable);
        }

        public void DeliverPacket(Packet packet)
        {
            _PacketReader.RawPacket = packet;
            string message = _PacketReader.ReadString(Encoding.UTF8);
            if (message != "Hello World") throw new Exception("Message invalid");
        }

        public Packet CollectPacket()
        {
            if (_OutgoingPacketCounter > 0)
            {
                _OutgoingPacketCounter--;
                return _TestPacket;
            }

            return null;
        }
        public void Initialize(NetBase host)
        {
            _NetServer = (NetServer)host;
            _NetServer.BeforeUpdate += new EventHandler(_NetServer_BeforeUpdate);
        }

        void _NetServer_BeforeUpdate(object sender, EventArgs e)
        {
            _OutgoingPacketCounter = PacketsPerUpdate;

        }       
    }
}
